package com.example.demo.config;

import com.baomidou.mybatisplus.extension.api.R;
import com.example.demo.annotation.Auth;
import com.example.demo.domain.dto.UserLoginDto;
import com.example.demo.enums.UserPermission;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;

@Slf4j
public class AuthInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            try {
                Auth auth = ((HandlerMethod) handler).getMethodAnnotation(Auth.class);
                if (auth != null) {
                    UserPermission value = auth.value();
                    UserLoginDto userLoginDto = (UserLoginDto) request.getSession().getAttribute(LoginInterceptor.USER_KEY);
                    for (UserPermission permission : userLoginDto.getPermissions()) {
                        if (auth.value() == permission) {
                            return true;
                        }
                    }
                }
                log.info("permission denied, auth={}", auth.value());
                R r = R.failed("permission denied");
                response.getOutputStream().write((new Gson().toJson(r)).getBytes(StandardCharsets.UTF_8));
            } catch (Exception e) {
                log.error("catch exception:", e);
            }
        }
        return true;
    }
}
